package com.wt.admin.util;


import java.security.SecureRandom;
import java.util.*;

public class SecureCodeUtil {

    // 字符集：使用0-9、A-Z、a-z，避免易混淆字符
    private static final String CHARACTERS = "@%^&*$#0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final SecureRandom secureRandom = new SecureRandom();

    // 生成指定长度的原始字符串
    public static String generateAString(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("长度必须为正数");
        }

        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = secureRandom.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }

    // 生成随机种子
    public static int generateSeed() {
        return secureRandom.nextInt();
    }

    /**
     * 从原始字符串中抽取子串
     * @param aString 原始字符串
     * @param extractLen 抽取长度
     * @param seed 随机种子
     * @return
     */
    public static String extractSubstring(String aString, int extractLen, int seed) {
        if(aString == null || aString.length() < extractLen){
            return null;
        }
        // 使用线性同余生成器(LCG)确保前后端算法一致
        final long modulus = 1L << 32;
        final long a = 1664525;
        final long c = 1013904223;
        long current = seed;
        Set<Integer> indices = new HashSet<>();
        // 生成不重复的索引
        while (indices.size() < extractLen) {
            current = (a * current + c) % modulus;
            // 映射到0-59的范围
            int index = (int) (current % aString.length());
            indices.add(index);
        }
        // 排序索引并提取字符
        List<Integer> sortedIndices = new ArrayList<>(indices);
        Collections.sort(sortedIndices);
        StringBuilder subString = new StringBuilder();
        for (int index : sortedIndices) {
            subString.append(aString.charAt(index));
        }
        return subString.toString();
    }

}
